package com.shawn.gateway.filter;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * @author shawn
 * @date 2022年 11月 30日 18:48
 */

@Slf4j
@Component
public class MallGlobalFilter implements GlobalFilter, Ordered {

    @Value("${gateway.excludedUrls}")
    private ArrayList<String> excludeUrls;


    @Resource
    private RestTemplate restTemplate;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        //过滤请求
        String path = request.getURI().getPath();
        log.info("拦截到路径:{}",path);
        if (excludeUrls.contains(path)){
            return chain.filter(exchange);
        }
        //获取token
        String token = request.getHeaders().getFirst("Authorization");
        //如果token为空则返回错误页面
        if (StringUtils.isEmpty(token)){
            ServerHttpResponse response = exchange.getResponse();
            //token失效,响应错误码
            Map<String, Object> responseData = new HashMap<>();
            responseData.put("code", 401);
            responseData.put("message", "用户未登录");
            return responseError(response,responseData);
        }

        token = token.replace("Bearer ", "");
        //验证token
        String url = "http://localhost:18080/admin/parseToken/"+token;
        String info = restTemplate.getForObject(url, String.class);

        if (info==null){
            ServerHttpResponse response = exchange.getResponse();
            //token失效,响应错误码
            Map<String, Object> responseData = new HashMap<>();
            responseData.put("code", 401);
            responseData.put("message", "token以失效!");
            return responseError(response,responseData);
        }

        ServerHttpRequest serverHttpRequest = request.mutate().
                headers(httpHeaders -> httpHeaders.add("info", info)).build();
        //重置请求
        exchange.mutate().request(serverHttpRequest);
        return chain.filter(exchange);
    }

    private Mono<Void> responseError(ServerHttpResponse response, Map<String, Object> responseData){
        // 将信息转换为 JSON
        ObjectMapper objectMapper = new ObjectMapper();
        byte[] data = new byte[0];
        try {
            data = objectMapper.writeValueAsBytes(responseData);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        // 输出错误信息到页面
        DataBuffer buffer = response.bufferFactory().wrap(data);
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }

    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;
    }
}